package me.evis.gae.guestbook.bo.dao;

import java.util.ArrayList;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;

import me.evis.gae.data.PersistenceManagerFactorySingleton;
import me.evis.gae.guestbook.bo.Comment;

import org.apache.log4j.Logger;

public class CommentDao {
    
    private static final Logger logger = Logger.getLogger(CommentDao.class);
	
	private static PersistenceManagerFactory pmf = 
		PersistenceManagerFactorySingleton.getInstance();
	
	public static Comment create(Comment comment) {
		Comment storedComment;
		PersistenceManager pm = pmf.getPersistenceManager();
		try {
			storedComment = pm.makePersistent(comment);
		} catch (Exception e) {
		    logger.error("Error occured when creating new Comment in DB. ", e);
			throw new RuntimeException(e);
		} finally {
			pm.close();
		}
		if (logger.isDebugEnabled()) {
		    logger.debug("Created new Comment in DB with ID: "
                             + storedComment.getId());
		}
		return storedComment;
	}
	
	public static List<Comment> retrieve() {
		List<Comment> comments = new ArrayList<Comment>();
		PersistenceManager pm = pmf.getPersistenceManager();
		String query = "SELECT FROM " + Comment.class.getName()
		                   + " ORDER BY createDate DESC";
		comments = (List<Comment>) pm.newQuery(query).execute();
        if (logger.isDebugEnabled()) {
            logger.debug("Retrieved all " + comments.size()
                             + " Comments from DB. ");
        }	
		return comments;
	}
	
}
